package com.ivy.builder.json;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ivy.builder.graph.Edge;
import com.ivy.builder.graph.LogicFlowData;
import com.ivy.builder.graph.Node;

import java.util.ArrayList;
import java.util.List;

public class IvyFlowBuilderJson {

    private LogicFlowData flowData = new LogicFlowData();

    public static IvyFlowBuilderJson NEW(){
        return new IvyFlowBuilderJson();
    }

    public IvyFlowBuilderJson addNode(IvyFlowBuilderNode... nodes){
        if(nodes == null || nodes.length == 0){
            throw new RuntimeException("不能添加空节点！");
        }
        List<Node> nodeList = flowData.getNodes();
        if(nodeList == null){
            nodeList = new ArrayList<>();
        }
        for (IvyFlowBuilderNode node : nodes){
            nodeList.addAll(new ArrayList<Node>(){{add(node.getNode());}});
        }
        flowData.setNodes(nodeList);
        return this;
    }

    public IvyFlowBuilderJson addEdge(IvyFlowBuilderNode sourceNode, IvyFlowBuilderNode targetNode){
        List<Edge> edgeList = flowData.getEdges();
        if(edgeList == null){
            edgeList = new ArrayList<>();
        }
        edgeList.add(IvyFlowBuilderEdge.NEW().sourceNode(sourceNode.getNode().getId())
                .targetNode(targetNode.getNode().getId()).text("").getEdge());
        flowData.setEdges(edgeList);
        return this;
    }

    public IvyFlowBuilderJson addEdge(IvyFlowBuilderNode sourceNode, IvyFlowBuilderNode targetNode, String text, IvyFlowBuilderEdgeProp edgeProp){
        List<Edge> edgeList = flowData.getEdges();
        if(edgeList == null){
            edgeList = new ArrayList<>();
        }
        edgeList.add(IvyFlowBuilderEdge.NEW().sourceNode(sourceNode.getNode().getId())
                .targetNode(targetNode.getNode().getId()).text(text).properties(edgeProp).getEdge());
        flowData.setEdges(edgeList);
        return this;
    }

    public IvyFlowBuilderJson addEdge(IvyFlowBuilderEdge edge){
        List<Edge> edgeList = flowData.getEdges();
        if(edgeList == null){
            edgeList = new ArrayList<>();
        }
        edgeList.add(edge.getEdge());
        flowData.setEdges(edgeList);
        return this;
    }

    public String toJson(){
        Gson gson = new Gson();
        return gson.toJson(flowData);
    }

    public String toFormatJson(){
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(flowData);
    }

    public LogicFlowData toFlowData(){
        return flowData;
    }
}
